﻿Imports System.Net
Imports System.IO

Public Class packages

    Public Class cli
        Public Sub New(Optional DefaultDirectory As String = "c:\wpi\apps")
            _DefaultAppDirectory = DefaultDirectory
        End Sub

        Public Sub UpdatePackages()
            Console.WriteLine("UPDATE ALL PACKAGES")
        End Sub

        Public Sub ListAvaliablePackages()
            SetConsoleColors(ConsoleColor.yellow)
            Console.WriteLine("Avaliable packages list:")
            SetConsoleColors(ConsoleColor.grey)
            Dim DB As New db
            Dim C As New OleDb.OleDbConnection With {.ConnectionString = DB.CS(DbPath)}
            Dim R As OleDb.OleDbDataReader
            R = DB.GetDataReader(C, "select *, (select reponame from repo where repo.id=pkga.id_repo) as repo from pkga order by pkgname")
            If Not IsNothing(R) Then
                If R.HasRows Then
                    SetConsoleColors(ConsoleColor.white)
                    Console.Write("{0,-25}", "Repo name")
                    Console.Write("{0,-25}", "Pkg name")
                    Console.Write("{0,-6}", "Major")
                    Console.Write("{0,-6}", "Minor")
                    Console.Write("{0,-4}", "x32")
                    Console.WriteLine("{0,-4}", "x64")
                    SetConsoleColors(ConsoleColor.grey)
                    While R.Read
                        Console.Write("{0,-25}", R("repo").ToString)
                        Console.Write("{0,-25}", R("pkgname").ToString)
                        Console.Write("{0,-6}", R("pkgmajor").ToString)
                        Console.Write("{0,-6}", R("pkgminor").ToString)
                        If CBool(R("pkg32").ToString) Then Console.Write("{0,-4}", " X ") Else Console.Write("{0,-4}", " ")
                        If CBool(R("pkg64").ToString) Then Console.WriteLine("{0,-4}", " X ") Else Console.WriteLine("{0,-4}", " ")
                    End While
                Else
                    Console.WriteLine("List empty")
                End If
            Else
                Console.WriteLine("Error fetching list")
            End If
        End Sub

        Public Sub ListInstalledPackages()
            SetConsoleColors(ConsoleColor.yellow)
            Console.WriteLine("Installed packages list:")
            SetConsoleColors(ConsoleColor.grey)
            Dim DB As New db
            Dim C As New OleDb.OleDbConnection With {.ConnectionString = DB.CS(DbPath)}
            Dim R As OleDb.OleDbDataReader
            R = DB.GetDataReader(C, "select * from pkgi order by pname")
            If Not IsNothing(R) Then
                If R.HasRows Then
                    SetConsoleColors(ConsoleColor.white)
                    Console.Write("{0,-20}", "Date added")
                    Console.Write("{0,-25}", "Pkg name")
                    Console.Write("{0,-6}", "Major")
                    Console.Write("{0,-6}", "Minor")
                    Console.WriteLine("Path")
                    SetConsoleColors(ConsoleColor.grey)
                    While R.Read
                        Console.Write("{0,-20}", R("dateadded").ToString)
                        Console.Write("{0,-25}", R("pname").ToString)
                        Console.Write("{0,-6}", R("major").ToString)
                        Console.Write("{0,-6}", R("minor").ToString)
                        Console.WriteLine(R("path").ToString)
                    End While
                Else
                    Console.WriteLine("List empty")
                End If
            Else
                Console.WriteLine("Error fetching list")
            End If
        End Sub

        Public Sub InstallPackage(PackageName As String, Arch As String)
            Dim PKGURL As String = ""
            Dim DB As New db
            Dim C As New OleDb.OleDbConnection With {.ConnectionString = DB.CS(DbPath)}
            Dim R As OleDb.OleDbDataReader
            R = DB.GetDataReader(C, "select * from pkga where pkgname='" & PackageName & "'")
            If Not IsNothing(R) Then
                If R.HasRows Then
                    While R.Read
                        PKGURL = R("pkgfile").ToString.Trim
                    End While
                Else
                    Console.WriteLine("Package not found in repo. Check Package name or update repos.")
                End If
            Else
                Console.WriteLine("Error fetching list")
            End If

            If PKGURL <> "" Then
                SetConsoleColors(ConsoleColor.yellow)
                Console.Write("Install pkg '" & PackageName & "'? [Y/N] ")
                SetConsoleColors(ConsoleColor.grey)
                Dim K As String = Console.ReadLine
                If K.ToLower <> "y" Then Exit Sub

                Dim S1 As Boolean = False
                Dim S2 As Boolean = False

                Dim webRequest As WebRequest
                Dim webresponse As WebResponse
                Dim inStream As StreamReader
                Try
                    webRequest = webRequest.Create(PKGURL)
                    S1 = True
                Catch ex As Exception
                    SetConsoleColors(ConsoleColor.red)
                    Console.WriteLine(ex.Message)
                    SetConsoleColors(ConsoleColor.grey)
                    Exit Sub
                End Try

                If S1 Then
                    SetConsoleColors(ConsoleColor.aqua)
                    Console.WriteLine("Package config file present.")
                    SetConsoleColors(ConsoleColor.grey)
                    Try
                        webresponse = webRequest.GetResponse()
                        S2 = True
                    Catch ex As WebException
                        SetConsoleColors(ConsoleColor.red)
                        Console.WriteLine(ex.Message)
                        SetConsoleColors(ConsoleColor.grey)
                        Exit Sub
                    End Try
                End If

                Dim PkgType As String
                Dim PkgArchive As String
                Dim PkgSetup As String
                Dim PkgParams As String
                Dim PkgPath As String
                Dim pkgAddTopath As Boolean = False

                If S2 Then
                    SetConsoleColors(ConsoleColor.aqua)
                    Console.WriteLine("Reading package install file...")
                    SetConsoleColors(ConsoleColor.grey)
                    Try
                        inStream = New StreamReader(webresponse.GetResponseStream())
                        Dim C2 As New OleDb.OleDbConnection With {.ConnectionString = DB.CS(DbPath)}
                        SetConsoleColors(ConsoleColor.aqua)
                        While Not inStream.EndOfStream
                            Dim a As String = inStream.ReadLine
                            Select Case True
                                Case a.Trim.ToLower.StartsWith("<pckg ")
                                    PkgType = GetXmlAttrib(a.Trim, "type")

                                Case a.Trim.ToLower.StartsWith("<archive" & Arch)
                                    PkgArchive = GetXmlElem(a.Trim)

                                Case a.Trim.ToLower.StartsWith("<setupfile" & Arch)
                                    PkgSetup = GetXmlElem(a.Trim)

                                Case a.Trim.ToLower.StartsWith("<params")
                                    PkgParams = GetXmlElem(a.Trim)

                                Case a.Trim.ToLower.StartsWith("<directory")
                                    PkgPath = GetXmlElem(a.Trim)

                                Case a.Trim.ToLower.StartsWith("<addtopath")
                                    pkgAddTopath = CBool(GetXmlElem(a.Trim))

                            End Select
                        End While
                    Catch ex As Exception
                        SetConsoleColors(ConsoleColor.red)
                        Console.WriteLine(ex.Message)
                        SetConsoleColors(ConsoleColor.grey)
                        Exit Sub
                    End Try
                End If
                Select Case PkgType
                    Case Is = "exe"
                        SetConsoleColors(ConsoleColor.pink)
                        Console.WriteLine("Warning! Selected package is an executable inistallation. wApt will not be able to update the package.")
                        Console.WriteLine("This package will not be registered as 'Installed' by wAPT. It will show in 'Programs and Features' instead.")
                        Console.Write("Proceed? [Y/N] ")
                        K = Console.ReadLine
                        SetConsoleColors(ConsoleColor.grey)
                        If K.ToLower <> "y" Then Exit Sub
                        DL(StripFileFromUrl(PKGURL) & PkgArchive)
                        If File.Exists(_DefaultAppDirectory & "\tmp.7z") Then
                            Extract(_DefaultAppDirectory & "\tmp.7z", _DefaultAppDirectory)
                            Try
                                File.Delete(_DefaultAppDirectory & "\tmp.7z")
                            Catch ex As Exception

                            End Try
                            Try
                                Dim PI As New ProcessStartInfo
                                PI.FileName = _DefaultAppDirectory & "\" & PkgSetup
                                PI.Arguments = PkgParams
                                Console.WriteLine(_DefaultAppDirectory & "\" & PkgSetup & " " & PkgParams)
                                PI.UseShellExecute = True
                                PI.WindowStyle = ProcessWindowStyle.Hidden
                                Dim P As Process = Process.Start(PI)
                                P.WaitForExit()
                                Try
                                    File.Delete(_DefaultAppDirectory & "\" & PkgSetup)
                                Catch ex As Exception

                                End Try
                            Catch ex As Exception
                                Console.WriteLine(ex.Message)
                            End Try

                        Else
                            SetConsoleColors(ConsoleColor.red)
                            Console.WriteLine("Apparently, there was some kind of error downloading the file.")
                            SetConsoleColors(ConsoleColor.grey)
                        End If

                    Case Is = "msi"
                        SetConsoleColors(ConsoleColor.pink)
                        Console.WriteLine("Warning! Selected package is a Windows Installer package. wApt will not be able to update the package.")
                        Console.WriteLine("This package will not be registered as 'Installed' by wAPT. It will show in 'Programs and Features' instead.")
                        Console.Write("Proceed? [Y/N]")
                        K = Console.ReadLine
                        SetConsoleColors(ConsoleColor.grey)
                        If K.ToLower <> "y" Then Exit Sub
                        'download all

                    Case Is = "wpi"
                        DL(StripFileFromUrl(PKGURL) & PkgArchive)
                        If File.Exists(_DefaultAppDirectory & "\tmp.7z") Then
                            Extract(_DefaultAppDirectory & "\tmp.7z", _DefaultAppDirectory)
                            If pkgAddTopath Then
                                Dim OldPath As String = Environment.GetEnvironmentVariable("Path")
                                Environment.SetEnvironmentVariable("Path", AppPath.Replace("bin", "apps\") & PkgPath & "\;" & OldPath, EnvironmentVariableTarget.Machine)
                            End If
                            Try
                                File.Delete(_DefaultAppDirectory & "\tmp.7z")
                            Catch ex As Exception

                            End Try

                        Else
                            SetConsoleColors(ConsoleColor.red)
                            Console.WriteLine("Apparently, there was some kind of error downloading the file.")
                            SetConsoleColors(ConsoleColor.grey)
                        End If

                End Select

            Else
                Console.WriteLine("Exiting.")
            End If
        End Sub

        Public Sub RemovePackage(PackageName As String)
            SetConsoleColors(ConsoleColor.yellow)
            Console.Write("Remove pkg '" & PackageName & "'? [Y/N] ")
            SetConsoleColors(ConsoleColor.grey)
            Dim K As String = Console.Read
            SetConsoleColors(ConsoleColor.grey)
            If Chr(K.ToLower) <> "y" Then Exit Sub
            Console.WriteLine("Removing pkg '" & PackageName & "'")
            'Dim OldPath As String = Environment.GetEnvironmentVariable("Path")
            'Environment.SetEnvironmentVariable("Path", AppPath.Replace("bin", "data\" & PkgArchive.Replace(".7z", "\;")) & OldPath, EnvironmentVariableTarget.Machine)

        End Sub

    End Class

    Public Class gui

    End Class

End Class
